<template>
  <section>
    <canvas ref="cav"/>
  </section>
</template>

<script>
import {getRandomColor} from "@/utils/tools";

export default {
  //圆形扩散、运动轨迹
  name: "canvas-expansion",
  mounted() {
    this.init()
  },
  methods: {
    init() {
      let cavDom = this.$refs.cav
      cavDom.width = window.innerWidth - 300
      cavDom.height = window.innerHeight - 544
      let ww = cavDom.width
      let wh = cavDom.height
      let ctx = cavDom.getContext('2d')

      //  定义圆类
      class Circle {
        constructor(x, y) {
          this.r = Math.random() * 6
          this.x = Math.random() * (ww - 30) + 30
          this.y = Math.random() * (wh - 30) + 30
          this.xv = (Math.random() - 0.5) * 20;
          this.yv = (Math.random() - 0.5) * 20;
          this.color = getRandomColor()
        }

        update() {
          this.r += 0.5;
          if (this.r > 30) {
            this.r = 0
          }
        }

        draw(x, y) {
          ctx.globalAlpha = 0.95;
          ctx.beginPath()
          ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2)
          ctx.lineWidth = 2; //线条宽度
          ctx.strokeStyle = 'rgba(250,250,50,1)'; //颜色
          ctx.stroke();
          ctx.closePath()
        }
      }

      let ciclesList = []
      for (let i = 0; i < ww; i += Math.round(ww / 4)) {
        ciclesList.push(new Circle())
      }

      function render() {
        //创建一个临时canvas来缓存主canvas的历史图像
        let backCanvas = document.createElement('canvas'),
            backCtx = backCanvas.getContext('2d');
        backCanvas.width = ww;
        backCanvas.height = wh;

        //显示即将绘制的图像，忽略临时canvas中已存在的图像
        backCtx.globalCompositeOperation = 'copy';
        //1.先将主canvas的图像缓存到临时canvas中
        backCtx.drawImage(cavDom, 0, 0, ww, wh);

        ctx.clearRect(0, 0, ww, wh)

        requestAnimationFrame(render)
        ciclesList.forEach(e => {
          e.draw()
          e.update()
        })
        //4.等新圆画完后，再把临时canvas的图像绘制回主canvas中
        ctx.drawImage(backCanvas, 0, 0, ww, wh);

      }

      requestAnimationFrame(render)


    }
  }
}
</script>

<style scoped>
canvas {
  box-sizing: border-box;
  border-radius: 8px;
  overflow: hidden;
  background-color: #000000;
}
</style>
